package com.atsmart.app.activity;

import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ProductAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.ProductGroupInfo;
import com.atsmart.app.model.ProductGroupListInfo;
import com.atsmart.app.model.ProductInfo;
import com.atsmart.app.model.ProductItemInfo;
import com.atsmart.app.model.ProductItemListInfo;
import com.atsmart.app.model.ProductListInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.ProductGroupSqlHelper;
import com.atsmart.app.sql.ProductItemSqlHelper;
import com.atsmart.app.sql.ProductSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;

public class ProductListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler,
		OnClickListener {
	private static final String TAG = ProductListActivity.class.getName();
	private ListView listView;
	private ProductGroupListInfo datasource;
	private ProductAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private EditText txtKeyword;
	private Button btnSearch;
	private String keyword;
	private Button btnMap;
	private Button btnRef;
	private ProductGroupSqlHelper psql = null;
	private boolean asyntaskIsFinished = true;
	private int gid = 0;
	private ProductSqlHelper pssql = null;
	private ProductItemSqlHelper isql = null;
	private NumberSqlHelper nsql = null;
	private Dialog dialog;
	private Context context;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_list_layout);
		context = this;
		dialog = DialogUtil.getLoadingDialog(context);
		init();
		psql = new ProductGroupSqlHelper();
		psql.open(BizApp.getInstance().getSqlHelper());
		totalRow = psql.getCount();

		pssql = new ProductSqlHelper();
		pssql.open(BizApp.getInstance().getSqlHelper());
		isql = new ProductItemSqlHelper();
		isql.open(BizApp.getInstance().getSqlHelper());
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
	}

	private void init() {
		txtKeyword = (EditText) findViewById(R.id.txt_keyword);
		btnSearch = (Button) findViewById(R.id.btn_search);
		btnRef = (Button) findViewById(R.id.btn_refresh);
		btnMap = (Button) findViewById(R.id.btn_history);
		btnMap.setBackgroundResource(R.drawable.btn_earth_press);
		btnMap.setVisibility(View.INVISIBLE);
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		btnMap.setOnClickListener(this);
		btnRef.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listview);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
			gid = bundle.getInt(PersistentKeyUtil.CLIENT_ID_STRING, 0);
		if (gid == 0) {
			// LinearLayout rootLayout = (LinearLayout) findViewById(R.id.mulu);
			// LinearLayout layout = (LinearLayout) LayoutInflater.from(this)
			// .inflate(R.layout.mulu, null);
			// rootLayout.addView(layout);
		} else {
			// LinearLayout layout = (LinearLayout) LayoutInflater.from(this)
			// .inflate(R.layout.top, null);
			// layout.setVisibility(View.INVISIBLE);
		}
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (adapter == null) {
					return;
				}
				ProductGroupInfo clientInfo = (ProductGroupInfo) adapter
						.getItem(position);
				if (clientInfo.getType() == 0) {
					
					Bundle bundle = new Bundle();
					bundle.putInt(PersistentKeyUtil.CLIENT_ID_STRING,
							clientInfo.getId());
					bundle.putString(PersistentKeyUtil.PRODUCT_MULU_NAME,
							clientInfo.getName());
					IntentUtil.redirectToNext(ProductListActivity.this,
							ProductListActivity.class,
							PersistentKeyUtil.CLIENT_ID_STRING,
							clientInfo.getId());
				} else {
					Log.e("TAG", "=======");
					Bundle bundle = new Bundle();
					bundle.putString(PersistentKeyUtil.PRODUCT_NAME, "");
					IntentUtil.redirectToNext(ProductListActivity.this,
							ProductDetailListActivity.class,
							PersistentKeyUtil.CLIENT_ID_STRING,
							clientInfo.getId());
				}

			}
		});
	}

	 
	private void getAddData() {
//		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductGroupListInfo>() {

			@Override
			protected ProductGroupListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = 1;
				pageInfo.end = 1000;
				return ServiceHelper.getInstance()
						.postData(ServiceHost.productGroup(),
								new Gson().toJson(pageInfo),
								ProductGroupListInfo.class);
			}

			@Override
			protected void runWithResult(ProductGroupListInfo result)
					throws Exception {
				if (result != null) {
					psql.deleteProduct();
					for (ProductGroupInfo info : result.getProducts()) {
						psql.addProductGroupInfo(info);
					}
				}else{
				}
//				hideLoading();
//				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ProductGroupListInfo result,
					int iErrorCode) throws Exception {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getAddDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void getAddDataByUrl2() {
//		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductGroupListInfo>() {

			@Override
			protected ProductGroupListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = 1;
				pageInfo.end = 1000;
				return ServiceHelper.getInstance()
						.postData(ServiceHost.productGroup(),
								new Gson().toJson(pageInfo),
								ProductGroupListInfo.class);
			}

			@Override
			protected void runWithResult(ProductGroupListInfo result)
					throws Exception {
				if (result != null) {
					psql.deleteProduct();
					for (ProductGroupInfo info : result.getProducts()) {
						psql.addProductGroupInfo(info);
					}
				}else{
				}
			}

			@Override
			protected void runWithError(ProductGroupListInfo result,
					int iErrorCode) throws Exception {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}

	private void getAddDetailData() {
//		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductListInfo>() {

			@Override
			protected ProductListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = 1;
				pageInfo.end = 1000;
				return ServiceHelper.getInstance().postData(
						ServiceHost.product(), new Gson().toJson(pageInfo),
						ProductListInfo.class);
			}

			@Override
			protected void runWithResult(ProductListInfo result)
					throws Exception {
				if (result != null) {
					for (ProductInfo info : result.getProducts()) {
						pssql.deleteAttribute(info.getProduct_id());
						if (info.getGid() != null && info.getGid().length() > 0) {
							String[] gids = info.getGid().split(",");
							for (int j = 0; j < gids.length; j++) {
								pssql.addProductInfo(info,
										Integer.valueOf(gids[j]));
							}
						}

					}
					
				}
				NumberResponseInfo at = nsql.getNumberByType(7);
				if (at == null) {
					at = new NumberResponseInfo();
					at.setLastTime(Calendar.getInstance().getTimeInMillis());
					at.setNumber(0);
					at.setType(7);
					nsql.addNumberInfo(at);
				} else {
					nsql.updateAttribute(0, 7);
				}
//				hideLoading();
//				finishedLoad(TAG);
				if (asyntaskIsFinished) {
					pageIndex = 0;
//					showLoading();
					getData(gid);
				}
			}

			@Override
			protected void runWithError(ProductListInfo result, int iErrorCode)
					throws Exception {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
//				loadingFailed(TAG, iErrorCode);
//				hideLoading();
				try{
					getAddDetailDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}
	
	private void getAddDetailDataByUrl2() {
//		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductListInfo>() {

			@Override
			protected ProductListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = 1;
				pageInfo.end = 1000;
				return ServiceHelper.getInstance().postData(
						ServiceHost.product(), new Gson().toJson(pageInfo),
						ProductListInfo.class);
			}

			@Override
			protected void runWithResult(ProductListInfo result)
					throws Exception {
				if (result != null) {
					for (ProductInfo info : result.getProducts()) {
						pssql.deleteAttribute(info.getProduct_id());
						if (info.getGid() != null && info.getGid().length() > 0) {
							String[] gids = info.getGid().split(",");
							for (int j = 0; j < gids.length; j++) {
								pssql.addProductInfo(info,
										Integer.valueOf(gids[j]));
							}
						}

					}
					
				}
				NumberResponseInfo at = nsql.getNumberByType(7);
				if (at == null) {
					at = new NumberResponseInfo();
					at.setLastTime(Calendar.getInstance().getTimeInMillis());
					at.setNumber(0);
					at.setType(7);
					nsql.addNumberInfo(at);
				} else {
					nsql.updateAttribute(0, 7);
				}
//				hideLoading();
//				finishedLoad(TAG);
				if (asyntaskIsFinished) {
					pageIndex = 0;
//					showLoading();
					getData(gid);
				}
			}

			@Override
			protected void runWithError(ProductListInfo result, int iErrorCode)
					throws Exception {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				loadingFailed(TAG, iErrorCode);
				hideLoading();
			}
		}.execute();
	}

	private void getUpdateItemData(final int item) {
		
		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductItemListInfo>() {

			@Override
			protected ProductItemListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				Item pageInfo = new Item();
				pageInfo.product_id = item;
				return ServiceHelper.getInstance().postData(
						ServiceHost.productitem(), new Gson().toJson(pageInfo),
						ProductItemListInfo.class);
			}

			@Override
			protected void runWithResult(ProductItemListInfo result)
					throws Exception {
				if (result != null) {
					isql.deleteAttribute(item);
					for (ProductItemInfo info : result.getProducts()) {
						isql.addProductItemInfo(info, item);
					}
				}
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ProductItemListInfo result,
					int iErrorCode) throws Exception {
				loadingFailed(TAG, iErrorCode);
				hideLoading();
			}
		}.execute();
	}

	@Override
	protected void onResume() {
		super.onResume();
//		if (BizApp.getInstance().isNetworkAvailable()
//				|| BizApp.getInstance().isWiFiActive()) {
//			login();
//		}
		if (asyntaskIsFinished) {
			pageIndex = 0;
			showLoading();
			getData(gid);
		}
	}

	public class Phone implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("phone")
		public String phone;
	}

	public class Item implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("product-id")
		public int product_id;
	}

	 
	private void getData(final int id) {
//		registerLoadStatus(TAG);
		Log.e("TAG", "gid: = " + gid);
		new ServiceAsynTask<ProductGroupListInfo>() {

			@Override
			protected ProductGroupListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				int begin = pageIndex * pageSize;
				gid = id;
				return psql.getProductGroupInfo(begin, pageSize, id);
			}

			@Override
			protected void runWithResult(ProductGroupListInfo result)
					throws Exception {
				if (result != null) {
					datasource = result;
					if(datasource!=null&&datasource.getProducts()!=null){
						for(ProductGroupInfo g:datasource.getProducts()){
							ProductListInfo pl=pssql.getProductInfoList(psql.getProductGroupIds(g));
							if(pl!=null&&pl.getProducts()!=null){
								g.setNums(pl.getProducts().size());
							}
						}
					}
					bindData();
				}
				asyntaskIsFinished = true;
				finishedLoad(TAG);
				hideLoading();
			}

			@Override
			protected void runWithError(ProductGroupListInfo result,
					int iErrorCode) throws Exception {
				asyntaskIsFinished = true;
				loadingFailed(TAG, iErrorCode);
			}
		}.execute();
	}

	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new ProductAdapter(datasource, this);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		totalRow = datasource.getRows();
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData(gid);
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

	private void showMap() {
		if (datasource == null) {
			return;
		}
		Bundle bundle = new Bundle();
		bundle.putSerializable(PersistentKeyUtil.CLIENTS_STRING, datasource);
		IntentUtil.redirectToNext(ProductListActivity.this,
				ClientsMapActivity.class, bundle);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (gid == 0) {
			if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
				DialogUtil.getExitAppDialog(this).show();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			showLoading();
			getAddData();
			getAddDetailData();
			pageIndex = 0;
			break;
		case R.id.btn_history:
			showMap();
			break;
		case R.id.btn_search:
			keyword = txtKeyword.getText().toString().trim();
			if (StringUtil.isEmptyOrNull(keyword)) {
				Toast.makeText(this, "请输入查询关键字", Toast.LENGTH_SHORT).show();
			} else {
				 showLoading();
				// getData(gid);
				Bundle bundle = new Bundle();
				bundle.putString(PersistentKeyUtil.PRODUCT_NAME, keyword);
				IntentUtil.redirectToNext(ProductListActivity.this,
						ProductDetailListActivity.class, bundle);
			}
			break;
		default:
			break;
		}
	}
}
